import React from 'react';
import { connect } from 'react-redux';
import { Toast } from 'antd-mobile';
import moment from 'moment';
import SubHeaderComponent from '../../../components/subHeader';
import WebMap from '../../../components/webMap';
import ColorCards from '../../../components/colorCards';
import ProgressBar from '../../../components/progressBar';
import RainTable from '../../../components/rainTable';
import SearchSite from '../../../components/searchSite';
import RainAnalysis from '../../../components/rainAnalysis';
import FootComponent from '../../../components/footComponent';
import Toolbar from '../../../components/toolBar';
import RbTools from '../../../components/rbTools';
import VoiceComponent from '../../../components/voiceComponent';
import Css from '../../../assets/css/home/main/index.css';
import * as utils from '../../../assets/js/utils/index';
import "react-step-progress-bar/styles.css";
import '../../../assets/css/common/public.css';

class Index extends React.Component {
    constructor(){
        super();
        this.state = {
            rainStyle: true,
            radarStyle: false,
            liveStyle: true,
            preStyle: false,
            showModal: false,
            siteStyle: false,
            locationStyle: false,
            isCarousel: false,
            aText: '最大降雨量站：XX站2.6mm,最小降雨量站：XX站1.6mm。',
            btnText: '雨情分析',
            aRainText: '昨天后半夜到目前，雄安新区和保定均出现降水天气，雄安新区平均降水量为19.2毫米，最大为市民服务中心站位26.1毫米，预计降水到今天前半夜基本结束。',
            time: utils.getLatestHours(),
            nowTime: moment().format('HH:mm'),
            showForcastModal: false,
            sForcast: '3H',
            percent: '0',
            predictTime: '',
            prePercent: 0,
            forcastTime: [
                { time: '72H', value: 72, checked: false },
                { time: '6H', value: 6, checked: false },
                { time: '3H', value: 3, checked: true },
            ],
            isShowRTable: false,
            isShowSite: false, //是否显示站点列表
            siteList: [ //站点列表数据
                {
                    name: '国家站',
                    list: [
                        { name: '安新站', value: 'anxin', checked: true },
                        { name: '容城站', value: 'anxin', checked: true },
                        { name: '雄县站', value: 'anxin', checked: true },
                    ]
                },
                {
                    name: '区域站',
                    list: [
                        { name: '安潼站', value: 'anxin', checked: false }
                    ]
                },
                {
                    name: '交通站',
                    list: [
                        { name: '淮阳站', value: 'anxin', checked: false }
                    ]
                }
            ],
            weather: '1' //当前天气
        }
    }
    
    componentDidMount(){
        this.getPercent();
    }

    //类型切换
    changeType(type){
        switch(type){
            case 'rain':
                this.setState({ rainStyle: true, radarStyle: false });
                break;
            case 'radar':
                this.setState({ rainStyle: false, radarStyle: true });
                break;
            default:
                this.setState({ rainStyle: true, radarStyle: false });
                break;
        }
    }

    //实况预报切换
    changeState(type){
        switch(type){
            case 'live':
                this.setState({ liveStyle: true, preStyle: false });
                break;
            case 'pre':
                this.setState({ liveStyle: false, preStyle: true });
                break;
            default:
                this.setState({ liveStyle: true, preStyle: false });
                break;
        }
    }

    //显示雨量分析提示框
    showRainModal(){
        this.setState({ showModal: true });
    }

    //关闭雨量分析提示框
    closeRainModal(){
        this.setState({ showModal: false });
    }

    //加载站点
    getSite(){
        this.setState({ siteStyle: !this.state.siteStyle });
    }

    //获取当前位置
    getLocation(){
        this.setState({ locationStyle: !this.state.locationStyle });
    }

    //时刻轮播
    carousel(){
        this.setState({ isCarousel: !this.state.isCarousel });
    }

    //选择预报时刻
    selectForcast(e, index){
        e.stopPropagation();
        const aForcastTime = utils.deepClone(this.state.forcastTime);
        aForcastTime.map(item => item.checked = false);
        aForcastTime[index].checked = true;
        const addTime = utils.addTime(this.state.time, aForcastTime[index].value);
        this.setState({ 
            forcastTime: aForcastTime, 
            sForcast: aForcastTime[index].time, 
            showForcastModal: false,
            time: addTime,
            nowTime: moment().format('HH:mm'),
            predictTime: '',
            prePercent: 0
        }, () => {  this.getPercent(); });
    }

    //显示预报时刻列表
    showListModal(e){
        if(e.target.getAttribute('target') === 'now'){
            this.setState({ showForcastModal: true });
        }
    }

    //设置当前时刻
    getPercent(){
        const { time, nowTime } = this.state;
        const startTime = moment(time[0].time, 'HH:mm');
        const endTime = moment(time.slice(-1)[0].time, 'HH:mm');
        const nowTimeMoment = moment(nowTime, 'HH:mm');
        const allMinutes = endTime.diff(startTime, 'minute');
        const nowMinutes = nowTimeMoment.diff(startTime, 'minute');
        const percent = Math.round((nowMinutes/allMinutes)*100).toFixed(2);
        this.setState({ percent });
    }

    //设置当前时刻
    setPointPosition({predictTime, prePercent}){
        this.setState({ predictTime, prePercent }, () => {
            // this.hideTime();
            this.setConStyle();
        });
    }

    //设置选择时刻为实况或预报
    setConStyle(){
        const { predictTime, nowTime } = this.state;
        const isPredict = moment(predictTime, 'HH:mm').isAfter(moment(nowTime, 'HH:mm'));
        const type = isPredict ? 'pre' : 'live';
        this.changeState(type);
    }

    //显示隐藏预报时刻
    hideTime(){
        const { time, predictTime } = this.state;
        const aTempTime = utils.deepClone(this.state.time);
        const preMoment = moment(predictTime, 'HH:mm');
        let index = 0;
        for(let i = 0, len = time.length; i < len; i++){
            if(moment(time[i].time, 'HH:mm').isAfter(preMoment)){
                index = i; break;
            }
        }
        aTempTime.map(item => item.hide = false);
        aTempTime[index].hide = true;
        this.setState({ time: aTempTime });
    }

    //显示同期降雨量列表
    showRainTable(){
        this.setState({ isShowRTable: true });
    }

    //隐藏同期降雨量列表
    hideRainTable(){
        this.setState({ isShowRTable: false });
    }

    //显示隐藏站点列表
    displaySiteBar(show){
        this.setState({ isShowSite: show });
    }

    //选择站点
    selectSite(index, kndex){
        const aTempSite = utils.deepClone(this.state.siteList);
        const checkedSites = utils.getSelectSite(aTempSite);
        if(checkedSites.length > 4){ 
            if(aTempSite[index]['list'][kndex]['checked']){
                aTempSite[index]['list'][kndex]['checked'] = false;
            }
        }else{
            aTempSite[index]['list'][kndex]['checked'] = !aTempSite[index]['list'][kndex]['checked'];
        }
        this.setState({ siteList: aTempSite }, () => {
            const checkedSites = utils.getSelectSite(this.state.siteList);
            if(checkedSites.length >= 5){ Toast.info('最多选择5个站点', 1); }
        });
    }

    componentWillUnmount(){
        //页面卸载时，重写setState,避免内存溢出
        this.setState = (state, callback) => {
            return ;
        }
    }

    //页面跳转
    goPage(url){
        this.props.history.push(window.base.config.path+url);
    }

    render() {
        const { 
            aText, aRainText, rainStyle, radarStyle, liveStyle, 
            preStyle, showModal, siteStyle, locationStyle, time,
            isCarousel, forcastTime, sForcast, showForcastModal,
            percent, nowTime, predictTime, prePercent, isShowRTable,
            isShowSite, siteList, weather
        } = this.state;
        const newProps = {
            percent,
            nowTime,
            predictTime,
            prePercent,
            list: time,
            carousel: isCarousel
        };
        return (
            <div className={Css['page']}>
                {/* 头部 */}
                <SubHeaderComponent title={liveStyle ? '雄安新区降雨实况' : '雄安新区降雨预报'} leftText="安新县" />
                <div className={Css['main']}>
                    {/* 色标 */}
                    <ColorCards></ColorCards>
                    {/* 地图 */}
                    <WebMap
                        location={locationStyle}
                        showRainSite={rainStyle}
                    >
                    </WebMap>
                    {/* 雨情提示 */}
                    <RainAnalysis
                        aText={aText}
                        aRainText={aRainText}
                        isLive={liveStyle}
                        showModal={showModal}
                        showTipsModal={() => this.showRainModal()}
                        closeTipsModal={() => this.closeRainModal()}
                    >
                    </RainAnalysis>
                    {/* 右上工具栏 */}
                    <Toolbar
                        rainStyle={rainStyle}
                        radarStyle={radarStyle}
                        liveStyle={liveStyle}
                        preStyle={preStyle}
                        changeToolType={(type) => this.changeType(type)}
                        changeToolState={(state) => this.changeState(state)}
                    >
                    </Toolbar>
                    {/* 右下工具栏 */}
                    <RbTools
                        isShow={isShowRTable}
                        siteStyle={siteStyle}
                        locationStyle={locationStyle}
                        loadSite={() => this.getSite()}
                        loadlocation={() => this.getLocation()}
                    >
                    </RbTools>
                    {/* 语音助手 */}
                    <VoiceComponent 
                        isShow={isShowRTable}
                    ></VoiceComponent>
                    {/* 实况预报时刻条 */}
                    <div className={isShowRTable ? Css['time-bar']+' '+Css['move'] : Css['time-bar']+' '+Css['unmove']}>
                        <div className={isCarousel ? Css['play-btn']+' '+Css['active'] : Css['play-btn']} onClick={() => this.carousel()}></div>
                        <div className={Css['slider']}>
                            <ProgressBar {...newProps} setPointPosition={(params) => this.setPointPosition(params)}></ProgressBar>
                        </div>
                        <div className={Css['time-select']}>
                            <span target="now" onClick={(e) => this.showListModal(e)}>{sForcast}</span>
                            <div className={showForcastModal ? Css['time-list'] : Css['time-list']+' hide'}>
                                {
                                    forcastTime.length > 0 ? forcastTime.map((item, index) => {
                                        return (
                                            <div key={index} className={item.checked ? Css['item']+' '+Css['active'] : Css['item']} onClick={(e) => this.selectForcast(e, index)}>{item.time}</div>
                                        )
                                    }) : ''
                                }
                                <div className={Css['item']+' '+Css['default']}>{sForcast}</div>
                            </div>
                        </div>
                    </div>
                    {/* 底部产品模块 */}
                    <FootComponent
                        weather={weather}
                        isShow={isShowRTable}
                        isLive={liveStyle}
                        showTable={() => this.showRainTable()}
                    >
                    </FootComponent>
                    {/* 同期降雨量列表 */}
                    <RainTable 
                        isShow={isShowRTable}
                        isShowSite={isShowSite}
                        siteList={siteList}
                        isLive={liveStyle}
                        closeTable={() => this.hideRainTable()}
                        showSiteBar={(show) => this.displaySiteBar(show)}
                    >
                    </RainTable>
                    {/* 站点选择列表 */}
                    <SearchSite
                        isShow={isShowSite}
                        siteList={siteList}
                        selectSite={(index, kndex) => this.selectSite(index, kndex)}
                        closeSite={(show) => this.displaySiteBar(show)}
                    >
                    </SearchSite>
                </div>
            </div>
        )
    }
}

export default connect((store) => {
    return store;
})(Index);